//
//  WBHomeViewModel.swift
//  sinaWeibo
//
//  Created by 吴熠 on 16/11/16.
//  Copyright © 2016年 吴熠. All rights reserved.
//

import UIKit
import YYModel
import SDWebImage

class WBHomeViewModel: NSObject {

    lazy var viewmodelArr : [WBStatusViewModel] = [WBStatusViewModel]()
    //懒加载一个存放wbstatus的模型数组
//    lazy var statusArr : [WBStatus] = [WBStatus]()//viewModel要引用model
    
    //加载数据,字典转模型
    //isPullup:是否正在上拉
    func loadData(isPullup:Bool, finished : @escaping (Bool,Int)->()){
        
        var maxId : Int64 = 0
        var sinceId : Int64 = 0
        if isPullup {
            //上拉
            maxId = viewmodelArr.last?.status?.id ?? 0
            if maxId != 0 {
                maxId -= 1
            }
        }else{
            sinceId = viewmodelArr.first?.status?.id ?? 0
        }
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let parameter = ["access_token" : WBUserAccountViewModel.shared.access_token,
                                    "max_id":"\(maxId)",
                                    "since_id":"\(sinceId)"]
        
        HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameter) { (responsObject, error) in
            if error != nil {
                return
            }
            //print(responsObject)
            //将responsObject转换为字典类型的数据
            let dict = responsObject as! [String : Any]
            //转换成字典类型的数组
            guard let array = dict["statuses"] as? [[String : Any]] else{
//                SVProgressHUD.showError(withStatus: "请求失败")
                return
            }
            //遍历转换出的数组,将里面的字典转成模型
//            var tempArr = [WBStatus]()
            var tempArr = [WBStatusViewModel]()
            for items in array {
                let viewModel = WBStatusViewModel()
    
                let s = WBStatus()
                s.yy_modelSet(with: items)
                viewModel.status = s
                tempArr.append(viewModel)
            }
            //执行成功的回调
            if isPullup {
                //上拉追加数据
                self.viewmodelArr = self.viewmodelArr + tempArr
            }else{
                //初次的时候直接赋值 下拉刷新将数据插入到最前面
                self.viewmodelArr = tempArr + self.viewmodelArr
                
            }
            
//            finished(true, tempArr.count)
            cacheForSingleImage(array: tempArr, finished: finished)
            
        }
    }
    

}

private func cacheForSingleImage(array:[WBStatusViewModel],finished:@escaping (Bool,Int)->()){
    
    if array.count == 0{
        finished(true, 0)//一定要回调
        return
    }
    
    let group = DispatchGroup()
    for viewModel in array{
        if viewModel.imgUrls?.count == 1{
        //入组
        group.enter()
        let urlString = viewModel.imgUrls?.first?.wap360 ?? ""
        let url = URL(string: urlString)
        SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
        //出租
            group.leave()
        })
        }
    }
    
    //统一回调
    group.notify(queue: DispatchQueue.main) {
        finished(true,array.count)
    }
    
}
